<script setup>
import { ref, onMounted, watch } from "vue";
import {
  queryAccommodationPageApi,
  checkinApi,
  checkoutApi,
  changeBedApi,
  queryAccommodationByIdApi,
} from "@/api/accommodation";
import { queryBuildingAllApi } from "@/api/building";
import { queryRoomListByBuildingApi } from "@/api/room";
import { queryBedListByRoomApi } from "@/api/bed";
import { queryStudentAllApi } from "@/api/student";
import { queryPageApi as queryEmpPageApi } from "@/api/emp";
import { ElMessage, ElMessageBox } from "element-plus";

// 人员类型下拉
const personTypes = [
  { name: "学员", value: 1 },
  { name: "员工", value: 2 },
];

// 楼栋/房间/床位下拉
const buildingList = ref([]);
const roomList = ref([]);
const bedList = ref([]);
const fetchBuildingList = async () => {
  const res = await queryBuildingAllApi();
  if (res.code) buildingList.value = res.data;
};
const fetchRoomList = async (buildingId) => {
  if (!buildingId) { roomList.value = []; return; }
  const res = await queryRoomListByBuildingApi(buildingId);
  if (res.code) roomList.value = res.data;
};
const fetchBedList = async (roomId) => {
  if (!roomId) { bedList.value = []; return; }
  const res = await queryBedListByRoomApi(roomId);
  if (res.code) bedList.value = res.data;
};

// 学员/员工下拉
const studentList = ref([]);
const empList = ref([]);
const fetchStudentList = async () => {
  const res = await queryStudentAllApi();
  if (res.code) studentList.value = res.data;
};
const fetchEmpList = async () => {
  const res = await queryEmpPageApi("", "", "", "", 1, 1000);
  if (res.code) empList.value = res.data.records;
};

// 查询表单
const searchForm = ref({
  personType: "",
  personId: "",
  buildingId: "",
  roomId: "",
  bedId: "",
  status: "",
  personName: "",
});

// 联动
watch(() => searchForm.value.buildingId, (val) => {
  searchForm.value.roomId = "";
  searchForm.value.bedId = "";
  fetchRoomList(val);
});
watch(() => searchForm.value.roomId, (val) => {
  searchForm.value.bedId = "";
  fetchBedList(val);
});

// 住宿列表、分页
const accommodationList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

const fetchAccommodationList = async () => {
  const params = {
    ...searchForm.value,
    page: currentPage.value,
    pageSize: pageSize.value,
  };
  const res = await queryAccommodationPageApi(params);
  if (res.code) {
    accommodationList.value = res.data.records;
    total.value = res.data.total;
  }
};

onMounted(() => {
  fetchBuildingList();
  fetchStudentList();
  fetchEmpList();
  fetchAccommodationList();
});

const handleSizeChange = () => fetchAccommodationList();
const handleCurrentChange = () => fetchAccommodationList();
const clear = () => {
  searchForm.value = { personType: "", personId: "", buildingId: "", roomId: "", bedId: "", status: "", personName: "" };
  fetchAccommodationList();
};

// 入住登记弹窗
const checkinDialogVisible = ref(false);
const checkinForm = ref({
  personType: 1,
  personId: "",
  bedId: "",
  checkinDate: "",
  deposit: 0,
  fee: 0,
  remark: "",
});
const checkinFormRef = ref();
const openCheckin = () => {
  checkinDialogVisible.value = true;
  checkinForm.value = { personType: 1, personId: "", bedId: "", checkinDate: "", deposit: 0, fee: 0, remark: "" };
  if (checkinFormRef.value) checkinFormRef.value.resetFields();
};
const saveCheckin = () => {
  checkinFormRef.value.validate(async (valid) => {
    if (!valid) return ElMessage.error("表单校验不通过");
    const res = await checkinApi(checkinForm.value);
    if (res.code) {
      ElMessage.success("登记成功");
      checkinDialogVisible.value = false;
      fetchAccommodationList();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 退宿
const handleCheckout = (row) => {
  ElMessageBox.confirm("确定要退宿吗？", "提示", { type: "warning" })
    .then(async () => {
      const res = await checkoutApi(row.id);
      if (res.code) {
        ElMessage.success("退宿成功");
        fetchAccommodationList();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

// 调宿弹窗
const changeDialogVisible = ref(false);
const changeForm = ref({ accommodationId: "", newBedId: "", remark: "" });
const changeFormRef = ref();
const openChange = (row) => {
  changeDialogVisible.value = true;
  changeForm.value = { accommodationId: row.id, newBedId: "", remark: "" };
};
const saveChange = () => {
  changeFormRef.value.validate(async (valid) => {
    if (!valid) return ElMessage.error("表单校验不通过");
    const res = await changeBedApi(changeForm.value.accommodationId, changeForm.value.newBedId, changeForm.value.remark);
    if (res.code) {
      ElMessage.success("调宿成功");
      changeDialogVisible.value = false;
      fetchAccommodationList();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 校验规则
const checkinRules = {
  personType: [{ required: true, message: "请选择人员类型", trigger: "change" }],
  personId: [{ required: true, message: "请选择人员", trigger: "change" }],
  bedId: [{ required: true, message: "请选择床位", trigger: "change" }],
  checkinDate: [{ required: true, message: "请选择入住日期", trigger: "change" }],
};
const changeRules = {
  newBedId: [{ required: true, message: "请选择新床位", trigger: "change" }],
};
</script>

<template>
  <div>
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline" style="margin-bottom: 16px">
      <el-form-item label="人员类型">
        <el-select v-model="searchForm.personType" placeholder="请选择类型" clearable>
          <el-option v-for="t in personTypes" :key="t.value" :label="t.name" :value="t.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名/工号/学号">
        <el-input v-model="searchForm.personName" placeholder="请输入姓名/工号/学号" clearable />
      </el-form-item>
      <el-form-item label="楼栋">
        <el-select v-model="searchForm.buildingId" placeholder="请选择楼栋" clearable>
          <el-option v-for="b in buildingList" :key="b.id" :label="b.name" :value="b.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="房间">
        <el-select v-model="searchForm.roomId" placeholder="请选择房间" clearable>
          <el-option v-for="r in roomList" :key="r.id" :label="r.roomNo" :value="r.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="床位">
        <el-select v-model="searchForm.bedId" placeholder="请选择床位" clearable>
          <el-option v-for="bed in bedList" :key="bed.id" :label="bed.bedNo" :value="bed.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchAccommodationList">查询</el-button>
        <el-button @click="clear">重置</el-button>
      </el-form-item>
      <el-form-item style="float:right; margin-left:auto;">
        <el-button type="primary" @click="openCheckin">+ 入住登记</el-button>
      </el-form-item>
    </el-form>

    <!-- 住宿表格 -->
    <el-table :data="accommodationList" border stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="personType" label="类型">
        <template #default="scope">
          {{ personTypes.find(t => t.value === scope.row.personType)?.name || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="personName" label="姓名" />
      <el-table-column prop="personNo" label="学号/工号" />
      <el-table-column prop="buildingName" label="楼栋" />
      <el-table-column prop="roomNo" label="房间号" />
      <el-table-column prop="bedNo" label="床位编号" />
      <el-table-column prop="checkinDate" label="入住日期" />
      <el-table-column prop="checkoutDate" label="退宿日期" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : scope.row.status === 2 ? 'info' : 'warning'">
            {{ scope.row.status === 1 ? '在住' : scope.row.status === 2 ? '已退' : '调宿' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button size="small" @click="openChange(scope.row)" :disabled="scope.row.status !== 1">调宿</el-button>
          <el-button size="small" type="danger" @click="handleCheckout(scope.row)" :disabled="scope.row.status !== 1">退宿</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      :page-sizes="[5, 10, 20, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 16px; text-align: right;"
    />

    <!-- 入住登记弹窗 -->
    <el-dialog v-model="checkinDialogVisible" title="入住登记" width="500px" @close="checkinFormRef?.resetFields()">
      <el-form :model="checkinForm" :rules="checkinRules" ref="checkinFormRef" label-width="100px">
        <el-form-item label="人员类型" prop="personType">
          <el-select v-model="checkinForm.personType" placeholder="请选择类型">
            <el-option v-for="t in personTypes" :key="t.value" :label="t.name" :value="t.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="人员" prop="personId">
          <el-select v-model="checkinForm.personId" placeholder="请选择人员">
            <el-option v-for="p in (checkinForm.personType === 1 ? studentList : empList)" :key="p.id" :label="p.name" :value="p.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="床位" prop="bedId">
          <el-select v-model="checkinForm.bedId" placeholder="请选择床位">
            <el-option v-for="bed in bedList" :key="bed.id" :label="bed.bedNo" :value="bed.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="入住日期" prop="checkinDate">
          <el-date-picker v-model="checkinForm.checkinDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="押金" prop="deposit">
          <el-input-number v-model="checkinForm.deposit" :min="0" />
        </el-form-item>
        <el-form-item label="住宿费" prop="fee">
          <el-input-number v-model="checkinForm.fee" :min="0" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="checkinForm.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="checkinDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCheckin">登记</el-button>
      </template>
    </el-dialog>

    <!-- 调宿弹窗 -->
    <el-dialog v-model="changeDialogVisible" title="调宿" width="400px" @close="changeFormRef?.resetFields()">
      <el-form :model="changeForm" :rules="changeRules" ref="changeFormRef" label-width="100px">
        <el-form-item label="新床位" prop="newBedId">
          <el-select v-model="changeForm.newBedId" placeholder="请选择新床位">
            <el-option v-for="bed in bedList" :key="bed.id" :label="bed.bedNo" :value="bed.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="调宿原因" prop="remark">
          <el-input v-model="changeForm.remark" placeholder="请输入调宿原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="changeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveChange">调宿</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
</style> 